package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.TbCategory;
import com.leyou.item.entity.TbCategoryBrand;
import com.leyou.item.mapper.TbCategoryBrandMapper;
import com.leyou.item.mapper.TbCategoryMapper;
import com.leyou.item.service.TbCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 商品类目表，类目和商品(spu)是一对多关系，类目与品牌是多对多关系 服务实现类
 * </p>
 *
 * @author HM
 * @since 2019-10-25
 */
@Service
public class TbCategoryServiceImpl extends ServiceImpl<TbCategoryMapper, TbCategory> implements TbCategoryService {

    @Autowired
    private TbCategoryMapper CategoryMapper;

    @Autowired
    private TbCategoryBrandMapper CategoryBrandMapper;

    @Override
    public List<CategoryDTO> queryListByParent(Long pid) {
        QueryWrapper<TbCategory> queryWrapper = new QueryWrapper<>();
       // queryWrapper.eq("parent_id",pid);
        queryWrapper.lambda().eq(TbCategory::getParentId,pid);
        List<TbCategory> categoryList = CategoryMapper.selectList(queryWrapper);
        if(CollectionUtils.isEmpty(categoryList)){
            throw  new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        /*对象转换，由TbCategory转化为DTO对象*/
        List<CategoryDTO> categoryDTOList = BeanHelper.copyWithCollection(categoryList, CategoryDTO.class);
        return categoryDTOList;
    }

    @Override
    public List<CategoryDTO> queryListByBrandId(Long id) {
        /*根据品牌id，查询分类信息*/
        /*
        * 1.先查询中间表，获取分类id集合
        * 2.再根据分类id集合，查询分类信息数据
        * 3.对象转换
        * */
        QueryWrapper<TbCategoryBrand> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TbCategoryBrand::getBrandId,id);
        List<TbCategoryBrand> categoryBrandList = CategoryBrandMapper.selectList(queryWrapper);
        List<Long> categoryIds=new ArrayList<>();
        for (TbCategoryBrand categoryBrand : categoryBrandList) {
            categoryIds.add(categoryBrand.getCategoryId());
        }
        List<TbCategory> categoryList = CategoryMapper.selectBatchIds(categoryIds);

        List<CategoryDTO> categoryDTOList = BeanHelper.copyWithCollection(categoryList, CategoryDTO.class);

        return categoryDTOList;
    }
}
